package com.netflix.appinfo;

import com.netflix.config.DynamicPropertyFactory;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class Archaius1VipAddressResolver implements VipAddressResolver {

    private static final Pattern VIP_ATTRIBUTES_PATTERN = Pattern.compile("\\$\\{(.*?)}");

    @Override
    public String resolveDeploymentContextBasedVipAddresses(String vipAddressMacro) {
        if (vipAddressMacro == null) {
            return null;
        }

        String result = vipAddressMacro;
        Matcher matcher = VIP_ATTRIBUTES_PATTERN.matcher(result);
        while (matcher.find()) {
            String key = matcher.group(1);
            String value = DynamicPropertyFactory.getInstance().getStringProperty(key, "").get();

            log.debug("att:{}", matcher.group());
            log.debug(", att key:{}", key);
            log.debug(", att value:{}", value);
            log.debug("");
            result = result.replaceAll("\\$\\{" + key + "}", value);
            matcher = VIP_ATTRIBUTES_PATTERN.matcher(result);
        }

        return result;
    }
}
